package com.sf.fy.uav.applet.order.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.sf.fy.uav.common.request.operate.ErrandOrderReq;
import com.sf.fy.uav.common.response.order.ErrandOrderResp;
import com.sf.fy.uav.common.response.order.ErrandOrderStatusResp;
import com.sf.fy.uav.common.utils.RespJsonPageData;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.order.controller.ErrandOrderRest;
import com.sf.fy.uav.rest.SysTcRest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 同城跑腿订单控制器
 */
@RestController
@RequestMapping("/home/errand/")
@RequiredArgsConstructor
@Api(tags = "同城跑腿订单管理")
public class ErrandsOrderController {

    private final static Logger logger = LoggerFactory.getLogger(ErrandsOrderController.class);

    private final ErrandOrderRest errandOrderRest;
    private final SysTcRest sysTcRest;

    @ApiOperation(value = "同城跑腿订单分页查询", notes = "根据同城订单号、丰翼订单号、订单创建时间和订单状态查询同城跑腿订单分页信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页大小", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderInquiryEntry", value = "订单查询入口(0代表月结，1代表运控)", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "tcWayBillNo", value = "同城订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fyWayBillNo", value = "丰翼订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderStartDate", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderEndDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "exportOrNot", value = "是否导出", dataType = "Boolean", paramType = "query"),
    })
    @GetMapping("get-errand-order-list")
    public RespJsonPageData<ErrandOrderResp> getErrandOrderList(@RequestParam Integer page,
                                                                @RequestParam Integer size,
                                                                @RequestParam Integer orderInquiryEntry,
                                                                @RequestParam(required = false) String tcWayBillNo,
                                                                @RequestParam(required = false) String fyWayBillNo,
                                                                @RequestParam(required = false) Integer orderStatus,
                                                                @RequestParam(required = false) String orderStartDate,
                                                                @RequestParam(required = false) String orderEndDate) {
        ErrandOrderReq errandOrderReq = new ErrandOrderReq();
        errandOrderReq.setPage(page);
        errandOrderReq.setSize(size);
        errandOrderReq.setTcWayBillNo(tcWayBillNo);
        errandOrderReq.setFyWayBillNo(fyWayBillNo);
        errandOrderReq.setStatus(orderStatus);
        errandOrderReq.setOrderStartDate(orderStartDate);
        errandOrderReq.setOrderEndDate(orderEndDate);
        errandOrderReq.setOrderInquiryEntry(orderInquiryEntry);
        return errandOrderRest.getErrandOrderList(errandOrderReq);
    }


    @ApiOperation(value = "根据丰翼订单号查询订单状态记录", notes = "根据丰翼订单号查询订单状态记录")
    @ApiImplicitParam(name = "id", value = "id", dataType = "String", paramType = "query")
    @GetMapping("get-status-log-list")
    public Rs<ErrandOrderStatusResp> getStatusLogList(@RequestParam String id) {
        ErrandOrderReq errandOrderReq = new ErrandOrderReq();
        errandOrderReq.setId(id);
        return errandOrderRest.getStatusLogList(errandOrderReq);
    }

    @GetMapping("export")
    @ApiOperation(value = "导出", notes = "/export")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页大小", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderInquiryEntry", value = "订单查询入口(0代表月结，1代表运控)", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "tcWayBillNo", value = "同城订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fyWayBillNo", value = "丰翼订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderStartDate", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderEndDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "exportOrNot", value = "是否导出", dataType = "Boolean", paramType = "query"),
    })
    public void export(HttpServletResponse response,
                       @RequestParam Integer page,
                       @RequestParam Integer size,
                       @RequestParam Integer orderInquiryEntry,
                       @RequestParam(required = false) String tcWayBillNo,
                       @RequestParam(required = false) String fyWayBillNo,
                       @RequestParam(required = false) Integer orderStatus,
                       @RequestParam(required = false) String orderStartDate,
                       @RequestParam(required = false) String orderEndDate) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            String fileName = "同城跑腿订单明细表" + sdf.format(new Date());
            response.setHeader("content-disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8) + ".xls");
            ExportParams exportParams = new ExportParams();
            RespJsonPageData<ErrandOrderResp> errandOrderListPage = this.getErrandOrderList(page, size, orderInquiryEntry, tcWayBillNo, fyWayBillNo, orderStatus, orderStartDate, orderEndDate);
            for (ErrandOrderResp errandOrderResp : errandOrderListPage.getResponseData()) {
                if (ObjectUtils.allNotNull(errandOrderResp.getTotalPaymentAmount()) && errandOrderResp.getTotalPaymentAmount().compareTo(BigDecimal.ZERO) > 0) {
                    errandOrderResp.setTotalPaymentAmount(errandOrderResp.getTotalPaymentAmount().setScale(2, RoundingMode.UP));
                }
                if (ObjectUtils.allNotNull(errandOrderResp.getPricePaid()) && errandOrderResp.getPricePaid().compareTo(BigDecimal.ZERO) > 0) {
                    errandOrderResp.setPricePaid(errandOrderResp.getPricePaid().setScale(2, RoundingMode.UP));
                }
                if (ObjectUtils.allNotNull(errandOrderResp.getTotalCouponAmount()) && errandOrderResp.getTotalCouponAmount().compareTo(BigDecimal.ZERO) > 0) {
                    errandOrderResp.setTotalCouponAmount(errandOrderResp.getTotalCouponAmount().setScale(2, RoundingMode.UP));
                }
            }
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ErrandOrderResp.class, errandOrderListPage.getResponseData());
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @ApiOperation(value = "查询骑手手机号码", notes = "根据同城跑腿订单号查询骑手明文手机号码")
    @ApiImplicitParam(name = "id", value = "id", dataType = "String", paramType = "query")
    @GetMapping("get-decode-phone")
    public Rs<String> getDecodePhone(@RequestParam String id) {
        return errandOrderRest.getDecodePhone(id);
    }
}
